package com.yaDuo.common.util;

import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

import androidx.annotation.StringRes;

import com.yaDuo.common.ui.GlobalContext;

/**
 * Toast 工具
 */
public class ToastUtils {

    private static final String TAG = "ToastUtils";
    public static final SDKToastHelper _helper = new SDKToastHelper();

    private static class SDKToastHelper {
        private final Handler _handler;
        public static volatile Toast _toast;
        public static volatile Toast _squareToast;

        SDKToastHelper() {
            _handler = new Handler(Looper.getMainLooper());
        }

        public void show(final String message, final int duration) {
            if (null == message)
                return;
            if (Looper.getMainLooper() != Looper.myLooper()) {
                _handler.post(() -> {
                    show(message, duration);
                });
                return;
            }
            if (_toast != null) {
                try {
                    _toast.cancel();
                } catch (Exception e) {
                    // ignore
                }
            }
            LogUtil.d(TAG, "toast message=" + message);
            try {
                _toast = Toast.makeText(GlobalContext.get(), message, duration);
                _toast.show();
            } catch (Exception e) {
                e.printStackTrace();
                LogUtil.e(TAG, "show Toast error " + e.getMessage());
            }
        }
    }

    public static void show(String message) {
        show(message, Toast.LENGTH_SHORT);
    }

    public static void show(@StringRes int message) {
        show(GlobalContext.get().getResources().getString(message), Toast.LENGTH_SHORT);
    }

    public static void show(final String message, final int duration) {
        if (null == message)
            return;
        _helper.show(message, duration);
    }

}
